package com.tuanzi.loan.web.bean.system;

import static com.google.common.base.Preconditions.checkArgument;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tuanzi.loan.business.entity.system.UserRole;
import com.tuanzi.loan.business.service.system.RoleService;
import com.tuanzi.loan.business.service.system.UserRoleService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.system.RoleSearchRequest;
import com.tuanzi.loan.vo.response.system.RoleSearchResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.system.RoleLazyDataModel;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author Ray 2017/09/21
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class UserRoleRelationBean extends JSFListingBean<RoleSearchRequest, RoleSearchResponse> {

    private static final long serialVersionUID = 30992312030673477L;

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    private String userId;

    @PostConstruct
    private void init() {
        userId = getParamFromRequest("id");
        checkArgument(StringUtils.isNotBlank(userId));
        initLazyDataModel();
    }

    public void onReset() {
        initLazyDataModel();
    }

    public void onRelateRole(String roleId) {
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        userRoleService.saveOrUpdate(userRole);
    }

    public void onUnrelateRole(String roleId) {
        UserRole userRole = userRoleService.findByUserIdAndRoleId(userId, roleId);
        userRoleService.delete(userRole);
    }

    private void initLazyDataModel() {
        $ = new RoleSearchRequest();
        $.setUserId(userId);
        lazyDataModel = new RoleLazyDataModel($);
    }
}
